<?php

namespace App\Admin\Http\Controllers\Rbac;

use Flash;
use App\Admin\Eloquent\Role;
use App\Admin\Eloquent\Permission;
use App\Admin\Eloquent\RolePermission;
use App\Admin\Http\Requests\RoleRequest;
use App\Admin\Http\Controllers\Controller;
use App\Extensions\Pagination\BootstrapThreePresenter;
use Illuminate\Http\Request;
use Exception;
use DB;

class RolesController extends Controller
{
    /**
     * 角色列表信息
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = $request->only('search');

        $roles = Role::paginateQuery($query);

        // 追加分页查询条件
        if (!empty($query)) {
            $roles->appends($query);
        }

        // 分页查询代码
        $links = (new BootstrapThreePresenter($roles))->render();

        return view('admin.rbac.roles.index', compact('roles', 'query', 'links'));
    }

    /**
     * 角色详细信息
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $role = $this->role($id);

        return view('admin.rbac.roles.show', compact('role'));
    }

    /**
     * 新增角色信息表单
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.rbac.roles.create');
    }

    /**
     * 新增角色信息
     *
     * @param  \App\Admin\Http\Requests\RoleRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(RoleRequest $request)
    {
        $role = new Role($request->input());

        $role->save();

        Flash::success('新增角色信息成功');

        return $this->redirectAction('Rbac\RolesController@show', [$role]);
    }

    /**
     * 编辑角色信息表单
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = $this->role($id);

        return view('admin.rbac.roles.edit', compact('role'));
    }

    /**
     * 修改角色信息
     *
     * @param  mixed  $id
     * @param  \App\Admin\Http\Requests\RoleRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function update($id, RoleRequest $request)
    {
        $role = $this->role($id);

        $role->update($request->input());
        $role->cleanCachedPermissions();//清除权限缓存

        Flash::success('修改角色信息成功');

        return $this->redirectAction('Rbac\RolesController@show', [$role]);
    }

    /**
     * 删除角色信息
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = $this->role($id);

        $role->delete();

        Flash::success('删除角色信息成功');

        return $this->redirectAction('Rbac\RolesController@index');
    }

    /**
     * 分配角色权限
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function permission($id){
        $role=$this->role($id);
        //当前角色拥有的权限
        $role_permission=RolePermission::where("role_id","=",$id)->lists('permission_id')->toArray();
        //全部权限
        $permissions = $this->getPermissionParents(Permission::get());
        return view('admin.rbac.roles.permission', compact('permissions', 'role','role_permission'));
    }
    /**
     * 保存角色权限
     * @param  [type]  $id 角色编号
     * @param  Request $q  [description]
     */
    public function savePermission($id,Request $q){
        $permissions=$q->input("item") ?: [];
        $role=$this->role($id);
        try {
            $data=array();
            DB::beginTransaction();
            //清空角色权限
            RolePermission::where("role_id","=",$id)->delete();
            foreach ($permissions as $p_id) {
                $data[]=array("role_id"=>$id,"permission_id"=>$p_id);
            }
            RolePermission::insert($data);

            $role->cleanCachedPermissions();
            DB::commit();
            Flash::success('权限分配成功');

            return $this->redirectAction('Rbac\RolesController@index');
        } catch (Exception $e) {
            DB::rollback();
            abort(500,$e->getMessage());
        }
    }

    /**
     * 通过角色 id 查找角色
     *
     * @param  mixed  $id
     * @return \App\Role
     */
    protected function role($id)
    {
        $role = Role::findOrFail($id);

        return $role;
    }
    /**
     * 获取父级权限
     *
     * @param  \Illuminate\Support\Collection $permissions
     * @param  int $pid
     * @param  int $level
     * @return Permission[]
     */
    protected function getPermissionParents($permissions, $pid = 0, $level = 0)
    {
        $collection = collect();

        foreach ($permissions->where('pid', $pid) as $permission) {
            $permission->level = $level;

            $collection->push($permission);

            $collection = $collection->merge($this->getPermissionParents($permissions, $permission->id, $level + 1));
        }

        return $collection;
    }
}